import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Smartphone, MessageSquare, ArrowLeft, Lock, User } from "lucide-react";
import { useUser } from "@/contexts/UserContext";
import { useToast } from "@/hooks/use-toast";
import { showSuccess } from "@/hooks/use-toast";

import { getCodeImg, sendSmsCode } from "@/api/common";

const Login = () => {
  // 登录模式：password（账户密码）/ phone（手机验证码）
  const [loginMode, setLoginMode] = useState<"password" | "phone">("password");

  // 账户密码登录
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  // 手机验证码登录
  const [phone, setPhone] = useState("");
  const [captchaInput, setCaptchaInput] = useState("");
  const [code, setCode] = useState("");
  const [codeUuid, setCodeUuid] = useState("");
  const [loading, setLoading] = useState({
    login: false,
    captchaImg: false,
  });
  const [countdown, setCountdown] = useState(0);
  const [codeSent, setCodeSent] = useState(false);

  const [imgpath, setImgpath] = useState("");
  const [imgUuid, setImgUuid] = useState("");

  // 验证状态
  const [errors, setErrors] = useState({
    username: "",
    password: "",
    phone: "",
    captcha: "",
    code: "",
  });

  const { login, loginByUserName } = useUser();
  const { toast } = useToast();
  const navigate = useNavigate();

  // 校验函数
  const phoneRegex = /^1[3-9]\d{9}$/;
  const isValidPhone = (phone: string) => phoneRegex.test(phone);
  const isValidCaptcha = (input: string) => input.length > 0;
  const isValidCode = (code: string) => code.length === 6;
  const isValidPassword = (code: string) => code.length >= 6;

  // 生成新的验证码
  const generateCaptcha = () => {
    getCodeImg().then((json: any) => {
      const { captchaEnabled, img, uuid } = json;
      if (captchaEnabled) {
        setImgpath(`data:image/gif;base64,${img}`);
        setImgUuid(uuid);
      }
    });
  };

  // 验证输入
  const validateInputs = () => {
    const newErrors = {
      username: "",
      password: "",
      phone: "",
      captcha: "",
      code: "",
    };

    // 页面模式：login（登录）/ register（注册）
    if (loginMode == "phone") {
      if (!phone) {
        newErrors.phone = "请输入手机号码";
      } else if (!isValidPhone(phone)) {
        newErrors.phone = "请输入正确的手机号码";
      }

      if (codeSent && !code) {
        newErrors.code = "请输入手机验证码";
      } else if (codeSent && !isValidCode(code)) {
        newErrors.code = "请输入6位验证码";
      }
    } else {
      if (!username) {
        newErrors.username = "请输入手机号码";
      } else if (!isValidPhone(username)) {
        newErrors.username = "请输入正确的手机号码";
      }

      if (!password) {
        newErrors.code = "请输输入密码";
      } else if (!isValidPassword(code)) {
        newErrors.code = "请输入6位验证码";
      }
    }
    setErrors(newErrors);
    return Object.values(newErrors).every((error) => !error);
  };

  // 发送验证码
  const handleSendCode = async () => {
    // 验证手机号和图片验证码
    if (!isValidPhone(phone)) {
      setErrors((prev) => ({ ...prev, phone: "请输入正确的手机号码" }));
      return;
    }

    if (!isValidCaptcha(captchaInput)) {
      setErrors((prev) => ({ ...prev, captcha: "图片验证码错误" }));
      return;
    }

    setErrors((prev) => ({ ...prev, phone: "", captcha: "", code: "" }));
    setLoading((prev) => ({ ...prev, captchaImg: true }));

    const codePost = await sendSmsCode({
      uuid: imgUuid,
      code: captchaInput,
      phone: phone,
    });
    setLoading((prev) => ({ ...prev, captchaImg: false }));
    if (codePost.code == 200) {
      setCodeUuid(codePost.data);

      setCodeSent(true);
      setCountdown(60);
      showSuccess(`验证码已发送至 ${phone}，请注意查收`, "验证码已发送");
    } else if (codePost.code == 500) {
      generateCaptcha();
    }

    // 倒计时
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 账户密码登录
  const handlePasswordLogin = async () => {
    if (!isValidPhone(username)) {
      setErrors((prev) => ({ ...prev, username: "请输入正确的手机号(账户)" }));
      return;
    }
    if (!isValidPassword(password)) {
      setErrors((prev) => ({ ...prev, password: "密码至少6个字符" }));
      return;
    }

    setLoading((prev) => ({ ...prev, login: true }));
    const isLogin = await loginByUserName(
      username,
      password,
      imgUuid,
      captchaInput
    );
    setLoading((prev) => ({ ...prev, login: false }));
    console.info(isLogin);
    if (isLogin.token) navigate("/");
  };

  // 手机验证码登录/注册
  const handlePhoneLogin = async () => {
    if (!validateInputs() || !codeSent) {
      return;
    }
    setLoading((prev) => ({ ...prev, login: true }));
    const isLogin = await login(phone, codeUuid, code);
    setLoading((prev) => ({ ...prev, login: false }));
    if (isLogin.token) {
      navigate("/");
    } else {
      generateCaptcha();
    }
  };

  // 输入变化处理
  const handlePhoneChange = (value: string) => {
    setPhone(value);
    if (errors.phone) {
      setErrors((prev) => ({ ...prev, phone: "" }));
    }
  };

  // 输入变化处理
  const handleUserNameChange = (value: string) => {
    setUsername(value);
    if (errors.username) {
      setErrors((prev) => ({ ...prev, username: "" }));
    }
  };

  // 输入变化处理
  const handlePasswordChange = (value: string) => {
    setPassword(value);
    if (errors.password) {
      setErrors((prev) => ({ ...prev, password: "" }));
    }
  };

  const handleCaptchaChange = (value: string) => {
    setCaptchaInput(value);
    if (errors.captcha) {
      setErrors((prev) => ({ ...prev, captcha: "" }));
    }
  };

  const handleCodeChange = (value: string) => {
    setCode(value);
    if (errors.code) {
      setErrors((prev) => ({ ...prev, code: "" }));
    }
  };

  // 获取焦点
  const handleFocus = (key: string) => {
    setErrors((prev) => ({ ...prev, [key]: "" }));
  };

  // 失去焦点
  const handleBlur = (key: string) => {
    let errorMsg = "";
    if (key == "phone") {
      if (!isValidPhone(phone)) {
        errorMsg = "请输入正确的手机号码";
      }
    } else if (key == "username") {
      if (!isValidPhone(username)) {
        errorMsg = "请输入正确的手机号码!";
      }
    } else if (key == "captcha") {
      if (!isValidCaptcha(captchaInput)) {
        errorMsg = "请输入图片验证码";
      }
    } else if (key == "code") {
      if (!isValidCode(code)) {
        errorMsg = "请输入6位验证码";
      }
    } else if (key == "password") {
      if (!isValidPassword(password)) {
        errorMsg = "密码长度不能小于6";
      }
    }
    setErrors((prev) => ({ ...prev, [key]: errorMsg }));
  };

  useEffect(() => {
    generateCaptcha();
  }, []);

  return (
    <div className="min-h-screen bg-[var(--gradient-secondary)] flex items-center justify-center p-4">
      <div className="w-full max-w-md space-y-6">
        {/* 返回按钮 */}
        <Button
          variant="ghost"
          onClick={() => navigate("/")}
          className="flex items-center gap-2 text-muted-foreground hover:text-foreground transition-[var(--transition-smooth)]"
        >
          <ArrowLeft className="h-4 w-4" />
          返回首页
        </Button>

        <Card className="shadow-[var(--shadow-elegant)] border-0 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/60">
          <CardHeader className="text-center space-y-4">
            <div className="mx-auto w-16 h-16 bg-[var(--gradient-primary)] rounded-full flex items-center justify-center shadow-[var(--shadow-button)]">
              {loginMode === "password" ? (
                <Lock className="h-8 w-8 text-primary-foreground" />
              ) : (
                <Smartphone className="h-8 w-8 text-primary-foreground" />
              )}
            </div>
            <div>
              <CardTitle className="text-2xl bg-[var(--gradient-primary)] bg-clip-text text-transparent">
                {loginMode === "password" ? "登录" : "注册"}
              </CardTitle>
              <CardDescription className="mt-2">
                {loginMode === "password"
                  ? "使用账户密码登录"
                  : "输入手机号码和验证码，新用户将自动注册" +
                    (loginMode === "phone" ? "登录" : "注册")}
              </CardDescription>
            </div>

            {/* 登录方式切换 */}
            <div className="flex gap-2 justify-center">
              <Button
                variant={loginMode === "password" ? "default" : "outline"}
                size="sm"
                onClick={() => setLoginMode("password")}
                className="flex items-center gap-1"
              >
                <Lock className="h-3 w-3" />
                账户密码
              </Button>
              <Button
                variant={loginMode === "phone" ? "default" : "outline"}
                size="sm"
                onClick={() => setLoginMode("phone")}
                className="flex items-center gap-1"
              >
                <Smartphone className="h-3 w-3" />
                手机验证码
              </Button>
            </div>
          </CardHeader>

          <CardContent className="space-y-6">
            {loginMode === "password" ? (
              // 账户密码登录表单
              <>
                {/* 用户名输入 */}
                <div className="space-y-2">
                  <Label htmlFor="username">账户名</Label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="username"
                      type="text"
                      placeholder="请输入账户名"
                      value={username}
                      onFocus={() => handleFocus("username")}
                      onBlur={() => handleBlur("username")}
                      onChange={(e) => {
                        handleUserNameChange(e.target.value);
                      }}
                      className={`pl-10 ${
                        errors.username
                          ? "border-destructive focus:ring-destructive"
                          : ""
                      }`}
                    />
                  </div>
                  {errors.username && (
                    <p className="text-sm text-destructive mt-1">
                      {errors.username}
                    </p>
                  )}
                </div>

                {/* 密码输入 */}
                <div className="space-y-2">
                  <Label htmlFor="password">密码</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="password"
                      type="password"
                      placeholder="请输入密码"
                      value={password}
                      onFocus={() => handleFocus("password")}
                      onBlur={() => handleBlur("password")}
                      onChange={(e) => {
                        handlePasswordChange(e.target.value);
                      }}
                      className={`pl-10 ${
                        errors.password
                          ? "border-destructive focus:ring-destructive"
                          : ""
                      }`}
                    />
                  </div>
                  {errors.password && (
                    <p className="text-sm text-destructive mt-1">
                      {errors.password}
                    </p>
                  )}
                </div>
                {/* 图片验证码和发送验证码 */}
                <div className="space-y-2">
                  <Label>图片验证码</Label>
                  <div className="flex gap-2 items-center">
                    <div className="relative">
                      <img
                        src={imgpath}
                        alt="验证码"
                        className={`h-10 w-[120px] border rounded cursor-pointer ${
                          !imgpath ? "opacity-0" : ""
                        }`}
                        onClick={generateCaptcha}
                      />
                    </div>
                    <Input
                      type="text"
                      placeholder="请输入验证码"
                      value={captchaInput}
                      onFocus={() => handleFocus("captcha")}
                      onBlur={() => handleBlur("captcha")}
                      onChange={(e) =>
                        handleCaptchaChange(
                          e.target.value.replace(/\D/g, "").slice(0, 2)
                        )
                      }
                      className={`flex-1 ${
                        errors.captcha ? "border-destructive" : ""
                      }`}
                    />
                  </div>
                  {errors.captcha && (
                    <p className="text-sm text-destructive mt-1">
                      {errors.captcha}
                    </p>
                  )}
                </div>
              </>
            ) : (
              // 手机验证码登录表单
              <>
                {/* 手机号输入 */}
                <div className="space-y-2">
                  <Label htmlFor="phone">手机号码</Label>
                  <Input
                    id="phone"
                    type="tel"
                    placeholder="请输入11位手机号码"
                    value={phone}
                    onFocus={() => handleFocus("phone")}
                    onBlur={() => handleBlur("phone")}
                    onChange={(e) =>
                      handlePhoneChange(
                        e.target.value.replace(/\D/g, "").slice(0, 11)
                      )
                    }
                    className={`text-center text-lg ${
                      errors.phone ? "border-destructive" : ""
                    }`}
                  />
                  {errors.phone && (
                    <p className="text-sm text-destructive mt-1">
                      {errors.phone}
                    </p>
                  )}
                </div>

                {/* 图片验证码和发送验证码 */}
                <div className="space-y-2">
                  <Label>图片验证码</Label>
                  <div className="flex gap-2 items-center">
                    <div className="relative">
                      <img
                        src={imgpath}
                        alt="验证码"
                        className={`h-10 w-[120px] border rounded cursor-pointer ${
                          !imgpath ? "opacity-0" : ""
                        }`}
                        onClick={generateCaptcha}
                      />
                    </div>
                    <Input
                      type="text"
                      placeholder="请输入验证码"
                      value={captchaInput}
                      onFocus={() => handleFocus("captcha")}
                      onBlur={() => handleBlur("captcha")}
                      onChange={(e) =>
                        handleCaptchaChange(
                          e.target.value.replace(/\D/g, "").slice(0, 2)
                        )
                      }
                      className={`flex-1 ${
                        errors.captcha ? "border-destructive" : ""
                      }`}
                    />
                    <Button
                      onClick={handleSendCode}
                      disabled={
                        loading.captchaImg ||
                        countdown > 0 ||
                        !isValidPhone(phone) ||
                        !isValidCaptcha(captchaInput)
                      }
                      className="hover:shadow-[var(--shadow-button)] transition-[var(--transition-smooth)] whitespace-nowrap"
                      size="default"
                    >
                      {loading.captchaImg ? (
                        <>
                          <MessageSquare className="h-4 w-4 mr-2 animate-pulse" />
                          发送中...
                        </>
                      ) : countdown > 0 ? (
                        `${countdown}s后重新发送`
                      ) : codeSent ? (
                        <>
                          <MessageSquare className="h-4 w-4 mr-2" />
                          重新发送
                        </>
                      ) : (
                        <>
                          <MessageSquare className="h-4 w-4 mr-2" />
                          发送验证码
                        </>
                      )}
                    </Button>
                  </div>
                  {errors.captcha && (
                    <p className="text-sm text-destructive mt-1">
                      {errors.captcha}
                    </p>
                  )}
                </div>

                {/* 手机验证码输入 */}
                <div className="space-y-2">
                  <Label htmlFor="code">手机验证码</Label>
                  <Input
                    id="code"
                    type="text"
                    placeholder="请输入6位验证码"
                    value={code}
                    onChange={(e) =>
                      handleCodeChange(
                        e.target.value.replace(/\D/g, "").slice(0, 6)
                      )
                    }
                    className={`text-center text-xl ${
                      errors.code ? "border-destructive" : ""
                    }`}
                    disabled={!codeSent}
                    onFocus={() => handleFocus("code")}
                    onBlur={() => handleBlur("code")}
                  />
                  {errors.code && (
                    <p className="text-sm text-destructive mt-1">
                      {errors.code}
                    </p>
                  )}
                </div>
              </>
            )}

            {/* 登录/注册按钮 */}
            {loginMode === "phone" ? (
              <Button
                onClick={handlePhoneLogin}
                disabled={loading.login || !codeSent || !isValidCode(code)}
                className="w-full hover:shadow-[var(--shadow-button)] transition-[var(--transition-smooth)]"
                size="lg"
              >
                {loading.login ? "验证中..." : "登录/注册"}
              </Button>
            ) : (
              <Button
                onClick={handlePasswordLogin}
                disabled={
                  loading.login ||
                  !isValidPassword(password) ||
                  !isValidPhone(username) ||
                  !isValidCaptcha(captchaInput)
                }
                className="w-full hover:shadow-[var(--shadow-button)] transition-[var(--transition-smooth)]"
                size="lg"
              >
                {loading.login ? "验证中..." : "登录"}
              </Button>
            )}

            {/* 切换登录/注册模式 */}
            <div className="text-center text-sm">
              {loginMode === "password" ? (
                <p className="text-muted-foreground">
                  还没有账号？
                  <Button
                    variant="link"
                    className="h-auto p-0 ml-1 text-primary"
                    onClick={() => setLoginMode("phone")}
                  >
                    立即注册
                  </Button>
                </p>
              ) : (
                <p className="text-muted-foreground">
                  已有账号？
                  <Button
                    variant="link"
                    className="h-auto p-0 ml-1 text-primary"
                    onClick={() => setLoginMode("password")}
                  >
                    去登录，手机验证码可直接登录
                  </Button>
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        <p className="text-xs text-center text-muted-foreground">
          登录即表示您同意我们的
          <Button variant="link" className="h-auto p-0 text-xs text-primary">
            服务条款
          </Button>
          和
          <Button variant="link" className="h-auto p-0 text-xs text-primary">
            隐私政策
          </Button>
        </p>
      </div>
    </div>
  );
};

export default Login;
